package com.msdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.msdp.dto.Result;
import com.msdp.entity.SeckillVoucher;
import com.msdp.entity.VoucherOrder;
import com.msdp.mapper.VoucherOrderMapper;
import com.msdp.service.ISeckillVoucherService;
import com.msdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msdp.utils.RedisWorker;
import com.msdp.utils.SimpleRedisLock;
import com.msdp.utils.UserHolder;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.msdp.utils.MessageConstants.*;
import static com.msdp.utils.MessageConstants.VOUCHER_STOCK_INSUFFICIENT;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedisWorker redisWorker;

    @Resource
    private RedissonClient redissonClient;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    @PostConstruct
    private void init(){
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }
    private class VoucherOrderHandler implements Runnable{
        String queueName = "stream.orders";
        @Override
        public void run() {
            while (true){
                try {
                    // 1. 获取消息队列中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS stream.orders >
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
                    );
                    // 2. 判断消息是否获取成功
                    if (list == null || list.isEmpty()){
                        // 2.1 获取失败说明没有消息，继续循环
                        continue;
                    }
                    // 3. 如果获取成功，可以下单
                    MapRecord<String, Object, Object> entries = list.get(0);
                    Map<Object, Object> value = entries.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    handlerVoucherOrder(voucherOrder);
                    // 4. ACK确认
                    stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", entries.getId());
                } catch (Exception e) {
                    log.error(String.valueOf(proxy == null));
                    log.error("处理消息异常", e);
                    handleException();
                }
            }


        }

        private void handleException() {
            while (true){
                try {
                    // 1. 获取pending-list消息队列中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 STREAMS stream.orders 0
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create(queueName, ReadOffset.from("0"))
                    );
                    // 2. 判断消息是否获取成功
                    if (list == null || list.isEmpty()){
                        // 2.1 获取失败说明没有消息，退出循环
                        break;
                    }
                    // 3. 如果获取成功，可以下单
                    MapRecord<String, Object, Object> entries = list.get(0);
                    Map<Object, Object> value = entries.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    handlerVoucherOrder(voucherOrder);
                    // 4. ACK确认
                    stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", entries.getId());
                } catch (Exception e) {
                    log.error("处理pending-list消息异常", e);
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException ex) {
                        throw new RuntimeException(ex);
                    }
                }
            }
        }

        /*
        private static final BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);
        private class VoucherOrderHandler implements Runnable{
            @Override
            public void run() {
                try {
                    VoucherOrder voucherOrder = orderTasks.take();
                    // 处理订单
                    handlerVoucherOrder(voucherOrder);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

            }
    */
        private void handlerVoucherOrder(VoucherOrder voucherOrder) {
            Long userId = voucherOrder.getUserId();
            RLock redisLock = redissonClient.getLock("lock:order:" + userId);
            boolean isLock = redisLock.tryLock();

            if (!isLock) {
                log.error("不可重复下单");
                return;
            }
            try {
                    createVoucherOrder(voucherOrder);
                } finally {
                    redisLock.unlock();
                }
        }
    }

    /**
     * 秒杀下单功能
     * @param voucherId
     * @return
     */
    private IVoucherOrderService proxy;
    @Override
    public Result seckillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        // 1. 判断优惠券是否存在
        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
        if (seckillVoucher == null) {
            // 2. 不存在->返回错误信息
            return Result.fail(VOUCHER_NOT_EXIST);
        }
        // 判断秒杀是否开始
        LocalDateTime beginTime = seckillVoucher.getBeginTime();
        if(beginTime.isAfter(LocalDateTime.now())){
            //  秒杀还未开始
            return Result.fail(VOUCHER_NOT_BEGIN);
        }
        LocalDateTime endTime = seckillVoucher.getEndTime();
        if(endTime.isBefore(LocalDateTime.now())){
            //  秒杀已经结束
            return Result.fail(VOUCHER_ALREADY_OVER);
        }
        Long id = UserHolder.getUser().getId();
        long nextId = redisWorker.nextId("order:");
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), id.toString(), String.valueOf(nextId)
        );
        // 获取执行结果
        int r = result.intValue();
        // 不为0代表下单失败
        if(r != 0){
            return Result.fail(r == 1 ? VOUCHER_STOCK_INSUFFICIENT : VOUCHER_OVERBOOKING);
        }
        proxy = (IVoucherOrderService) AopContext.currentProxy();

        return Result.ok(nextId);
    }

   /* @Override
    public Result seckillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        // 1. 判断优惠券是否存在
        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
        if (seckillVoucher == null) {
            // 2. 不存在->返回错误信息
            return Result.fail(VOUCHER_NOT_EXIST);
        }
        // 判断秒杀是否开始
        LocalDateTime beginTime = seckillVoucher.getBeginTime();
        if(beginTime.isAfter(LocalDateTime.now())){
            //  秒杀还未开始
            return Result.fail(VOUCHER_NOT_BEGIN);
        }
        LocalDateTime endTime = seckillVoucher.getEndTime();
        if(endTime.isBefore(LocalDateTime.now())){
            //  秒杀已经结束
            return Result.fail(VOUCHER_ALREADY_OVER);
        }
        Long id = UserHolder.getUser().getId();

        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), id.toString()
        );
        // 获取执行结果
        int r = result.intValue();
        // 不为0代表下单失败
        if(r != 0){
            return Result.fail(r == 1 ? VOUCHER_STOCK_INSUFFICIENT : VOUCHER_OVERBOOKING);
        }
        VoucherOrder voucherOrder = new VoucherOrder();
        long nextId = redisWorker.nextId("order:");
        voucherOrder.setId(nextId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);

        orderTasks.add(voucherOrder);

        proxy = (IVoucherOrderService) AopContext.currentProxy();

        return Result.ok(voucherOrder.getId());
    } */

//    public Result seckillVoucher(Long voucherId) {
//        // 1. 判断优惠券是否存在
//        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
//        if (seckillVoucher == null) {
//            // 2. 不存在->返回错误信息
//            return Result.fail(VOUCHER_NOT_EXIST);
//        }
//        // 判断秒杀是否开始
//        LocalDateTime beginTime = seckillVoucher.getBeginTime();
//        if(beginTime.isAfter(LocalDateTime.now())){
//            //  秒杀还未开始
//            return Result.fail(VOUCHER_NOT_BEGIN);
//        }
//        LocalDateTime endTime = seckillVoucher.getEndTime();
//        if(endTime.isBefore(LocalDateTime.now())){
//            //  秒杀已经结束
//            return Result.fail(VOUCHER_ALREADY_OVER);
//        }
//        // 3. 存在->获取库存
//        if (seckillVoucher.getStock() < 1){
//            // 4. 库存不足->返回错误信息
//            return Result.fail(VOUCHER_STOCK_INSUFFICIENT);
//        }
//
//        return createVoucherOrder(voucherId);
////        Long userId = UserHolder.getUser().getId();
////        SimpleRedisLock lock = new SimpleRedisLock("order:" + userId, stringRedisTemplate);
////        boolean isLock = lock.tryLock(1200L);
////        if (!isLock) {
////            return Result.fail("不可重复下单");
////        }
////
////        try {
////            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
////            return proxy.createVoucherOrder(voucherId);
////        } finally {
////            lock.unlock();
////        }
//
////        synchronized (userId.toString().intern()){
////            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
////            return proxy.createVoucherOrder(voucherId);
////        }
//
//    }

    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getId();
        int count = query().eq("user_id", userId).eq("voucher_id", voucherOrder.getVoucherId()).count();

        if(count > 0){
            return ;
        }
        // 5. 库存充足，更新数据库
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherOrder.getVoucherId())
                .gt("stock", 0)
                .update();
        if(!success){
            return ;
        }
        // 6. 新增优惠券订单表
//        VoucherOrder voucherOrder = new VoucherOrder();
//        voucherOrder.setUserId(UserHolder.getUser().getId());
//        voucherOrder.setVoucherId(voucherId);
//        voucherOrder.setId(redisWorker.nextId("order"));
        // 6. 返回订单id
        save(voucherOrder);

    }
//    @Transactional
//    public Result createVoucherOrder(Long voucherId) {
//        Long userId = UserHolder.getUser().getId();
//        int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
//
//        if(count > 0){
//            return Result.fail(VOUCHER_OVERBOOKING);
//        }
//        // 5. 库存充足，更新数据库
//        boolean success = seckillVoucherService.update()
//                                                .setSql("stock = stock - 1")
//                                                .eq("voucher_id", voucherId)
//                                                .gt("stock", 0)
//                                                .update();
//        if(!success){
//            return Result.fail(VOUCHER_UPDATE_FAILED);
//        }
//        // 6. 新增优惠券订单表
//        VoucherOrder voucherOrder = new VoucherOrder();
//        voucherOrder.setUserId(UserHolder.getUser().getId());
//        voucherOrder.setVoucherId(voucherId);
//        voucherOrder.setId(redisWorker.nextId("order"));
//        // 6. 返回订单id
//        save(voucherOrder);
//
//        return Result.ok(voucherOrder.getId());
//
//    }
}
